const jwt = require('jsonwebtoken');
require('dotenv').config();

function auth(req, res, next) {
  // Get token from header
  const token = req.header('x-auth-token');

  // Check if no token
  if (!token) {
    return res.status(401).json({ message: '无访问权限，请先登录' });
  }

  try {
    // Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // Add user from payload
    req.user = decoded;
    next();
  } catch (err) {
    res.status(401).json({ message: '登录已过期，请重新登录' });
  }
}

module.exports = auth; 